import fetch from 'dva/fetch';
import { browserHistory } from 'react-router';
import {getCookie} from './coockie';
import { message } from 'antd';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return true;
  }
  return false;
}
function parseErrorMessage({ data }) {
  const { status, message } = data;
  if (status === 'error') {
    throw new Error(message);
  }
  return { data };
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url, options, dataType ) {
  if (options === undefined) {
    options = {}
  }
  if (dataType === undefined) {
    dataType = 'json'
  }
  const t = getCookie("token")
  if (t === null && url !== '/api/login') {
    browserHistory.push('/login')
    return
  }
  options.headers = { 'Authorization': `Bearer ${t}`}
  const response = await fetch(url, options)
  if (response.status === 401) {
    browserHistory.push('/login')
    return
  }else if (response.status === 299) {
    browserHistory.push('/error')
    return
  }
  const isOk = checkStatus(response);
  if (isOk) {
    let data = null
    if (dataType==='json'){
        data=await response.json();
    }else if(dataType==='blob'){
        data=await response.blob();
    }else{
        data=await response.text();
    }
    return data;
  } else {
    let err=null
    try{
      err = await response.json();
    }catch(e){
      return null
    }
    if (err!==null) {
      throw new Error(`${err.message}`);
    }
  }
}

